package oss

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"gopkg.in/yaml.v2"
	"log"
	"os"
)

type OssClient struct {
	OssConfig OssInitConfig
	OssClient *oss.Client
	OssBucket *oss.Bucket
}

type OssInitConfig struct {
	Endpoint        string `yaml:"endpoint" json:"endpoint"`
	AccessKeyId     string `yaml:"accessKeyId" json:"accessKeyId"`
	AccessKeySecret string `yaml:"accessKeySecret" json:"accessKeySecret"`
	BucketName      string `yaml:"bucketName" json:"bucketName"`
	ExpireTime      int64  `yaml:"expireTime" json:"expireTime"`
}

type OssYamlConfig struct {
	Oss OssInitConfig `yaml:"OssConfig"`
}

func Init(configFilepath string) (*OssClient, error) {
	var Logger = log.Default()
	Logger.Println("开始读取oss配置文件！")
	file, err := os.ReadFile(configFilepath)
	if err != nil {
		Logger.Println(err)
		return nil, err
	}
	var config OssYamlConfig
	err = yaml.Unmarshal(file, &config)
	if err != nil {
		Logger.Println(err)
		return nil, err
	}
	Logger.Println("读取oss配置文件成功！")
	// 初始化配置文件
	var Client = new(OssClient)
	Client.OssConfig = OssInitConfig{
		Endpoint:        config.Oss.Endpoint,
		AccessKeyId:     config.Oss.AccessKeyId,
		AccessKeySecret: config.Oss.AccessKeySecret,
		BucketName:      config.Oss.BucketName,
		ExpireTime:      config.Oss.ExpireTime,
	}
	// 初始化oss client
	client, err := oss.New(fmt.Sprintf("https://%s", config.Oss.Endpoint), config.Oss.AccessKeyId, config.Oss.AccessKeySecret)
	if err != nil {
		Logger.Println(err)
		return nil, err
	}
	Client.OssClient = client
	Logger.Println("初始化OssClient成功！")
	// 初始化bucket
	bucket, err := client.Bucket(config.Oss.BucketName)
	if err != nil {
		Logger.Println(err)
		return nil, err
	}
	Client.OssBucket = bucket
	return Client, nil
}

// PublicBucketUploadFile 公开存储桶上传文件
func (h *OssClient) PublicBucketUploadFile(filename, filepath string) (url string, err error) {
	// oss bucket的第一位文件名，第二位是文件绝对路径
	err = h.OssBucket.PutObjectFromFile(filename, filepath)
	if err != nil {
		return "", err
	}
	url = fmt.Sprintf("https://%s.%s/%s", h.OssConfig.BucketName, h.OssConfig.Endpoint, filename)
	return
}

func (h *OssClient) PrivateBucketUploadFile(filename, filepath string) (signUrl string, err error) {
	signedURL, err := h.OssBucket.SignURL(filename, oss.HTTPGet, h.OssConfig.ExpireTime)
	// 设置默认时间 3600秒
	if h.OssConfig.ExpireTime == 0 {
		h.OssConfig.ExpireTime = 3600
	}
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	signUrl = signedURL
	return
}
